package cn.ac.cintcm.synonymous;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;

public class Packager {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		File f = new File("D:/source/syn/a.txt");
		Packager pkger = new Packager();
		List<String> ret = pkger.parseOutput(new FileInputStream(f));
		pkger.debugEnabled = false;
		pkger.pkgResources(ret, "D:/source/syn/target.jar");
		System.out.println("���");
	}

	private boolean debugEnabled;

	public List<String> parseOutput(InputStream in) throws IOException {
		List<String> ret = new ArrayList<String>();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		String line = reader.readLine();
		while (line != null) {
			if (line.matches("\\[Loaded .* from .*")) {
				if (debugEnabled)
					System.out.println("Matches:" + line);
				line = line.substring(8, line.indexOf(" from "));
				if (!ret.contains(line)) {
					ret.add(line);
				}
			} else {
				if (debugEnabled)
					System.out.println("UnMatches:" + line);
			}
			line = reader.readLine();
		}
		return ret;
	}

	public void pkgResources(List<String> res, String fileName) throws IOException {
		File f = new File(fileName);
		if (!f.exists()) {
			f.createNewFile();
		}
		byte[] buf = new byte[1024];
		JarOutputStream out = new JarOutputStream(
				new FileOutputStream(fileName));
		for (String s : res) {
			s = s.replace('.', '/') + ".class";
			if (debugEnabled) {
				System.out.println("adding: " + s);
			}
			InputStream in = this.getClass().getClassLoader()
					.getResourceAsStream(s);
			if (in == null) {
				System.out.println("open failure." + s);
			} else {
                out.putNextEntry(new ZipEntry(s));
				int w = in.read(buf);
				while (w >= 0) {
					out.write(buf, 0, w);
					w = in.read(buf);
				}
				in.close();
			}
		}
		out.finish();
		out.close();
	}
}